<?php
/**
 * tvb log db appender
==================================
<appender>db</appender>
<db>
	<out_class>DB</out_class>
	<host>202.126.52.8</host>
	<dbname>tvblog</dbname>
	<table>logsa2222</table>
	<username>test</username>
	<password></password>
	<port>3306</port>
</db>
==================================
 * @author William Hu <william.hu@achievo.com>
 * @version 1.0
 * @package TVBLog
 */

require_once 'TVB/Logger/Appender/Interface.php';
class TVB_Logger_Appender_DB implements TVB_Logger_Appender_Interface
{
	private static $dbh;
	private static $d;
	private static $table_name;

	private static function connect($db_info)
	{
		$now = date("Ymd");
		if(!isset(self::$dbh)){
			$port = isset($db_info['port']) && !empty($db_info['port']) ? $db_info['port'] : '3306';
			$dsn = "mysql:host={$db_info['host']};port={$port};dbname={$db_info['dbname']}";
			if(isset($db_info['table']) && !empty($db_info['table'])){
				self::$table_name = $db_info['table'];
			} else {
				self::$table_name = 'logs_'.$now;
			}
			try {
				self::$dbh = new PDO($dsn, $db_info['username'], $db_info['password']);
			} catch (PDOException $e) {
				require_once 'TVB/Logger/Exception.php';
				throw new TVB_Logger_Exception('Connection failed: ' . $e->getMessage());
			}
		}
		if (self::$d != $now){
			self::createTable(self::$table_name);
			self::$d = $now;
		}
		
		return self::$dbh;
	}
	
	public function write($log_entity)
    {
		$db_info = TVB_Logger_Config::get('db', $log_entity->category);
		self::connect($db_info);
		$when = date('Y-m-d H:i:s',strtotime($log_entity->when));
		$sql = "INSERT INTO ".self::$table_name." (log_category ,log_when ,log_who ,log_level ,log_request ,log_note ,log_result) VALUES (?, ?, ?, ?, ?, ?, ?)";
		$sth = self::$dbh->prepare($sql);
		$sth->bindParam('1', $log_entity->category, PDO::PARAM_STR);
		$sth->bindParam('2', $when, PDO::PARAM_STR);
		$sth->bindParam('3', $log_entity->who, PDO::PARAM_STR);
		$sth->bindParam('4', $log_entity->level, PDO::PARAM_STR);
		$sth->bindParam('5', $log_entity->request, PDO::PARAM_STR);
		$sth->bindParam('6', $log_entity->note, PDO::PARAM_STR);
		$sth->bindParam('7', $log_entity->result, PDO::PARAM_STR);
		$ret = $sth->execute();
		if (!$ret) {
			require_once 'TVB/Logger/Exception.php';
			throw new TVB_Logger_Exception('SQL failed: ' . print_r(self::$dbh->errorInfo()));
		}
		return TRUE;
    }
	
	private static function createTable($talbe_name)
	{
		$sql="CREATE TABLE IF NOT EXISTS `{$talbe_name}` (
		  `id` int(11) NOT NULL auto_increment,
		  `log_category` varchar(20) NOT NULL,
		  `log_when` datetime NOT NULL,
		  `log_who` varchar(20) NOT NULL,
		  `log_level` varchar(20) NOT NULL,
		  `log_request` text NOT NULL,
		  `log_note` text NOT NULL,
		  `log_result` text NOT NULL,
		  PRIMARY KEY  (`id`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8;";
		return self::$dbh->exec($sql);
	}
}
?>